package com.uchengwang.ui.base_ui.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.UCityConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.adapter.FeedbakAdapter;
import com.uchengwang.ui.cm_ui.release.ui.FastChoosePhotoActivity;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.ImageManagerUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;

/**
 * Created by U城网 on 2017/7/16.
 * 反馈上传详情页
 */

public class FeedbackDetailActivity extends AllBaseActivity implements View.OnClickListener{
    private ActivityTitleBar titleBar;
    private EditText edit;
    private GridView gv;
    private Button bt_release;
    private LinearLayout feedback_phone_ln;
    private EditText feedback_phone;
    private ArrayList<MediaBean> medias = new ArrayList<>();//返回多张图片地址
    private FeedbakAdapter adapter;

    private RelativeLayout choose_rl;//添加图片
    private List<String> imageList;//选择本地图片,得到的本地图片的集合 提交到oss
    private ScrollView feedback_sv;

    private String editContent, phoneString;
    private String pubTitle; //反馈模块标题
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_feedback_detail);
        pubTitle = getIntent().getStringExtra(BaseConfig.TITLE);

        initView();

    }

    private void initView() {
        feedback_sv = (ScrollView) findViewById(R.id.feedback_sv);
        feedback_sv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (UCommonUtil.getUtil().isShowSoftInput(FeedbackDetailActivity.this)){
                    UCommonUtil.getUtil().hideSoftInput(FeedbackDetailActivity.this, edit);
                }

                return false;
            }
        });

        titleBar = (ActivityTitleBar) findViewById(R.id.feedback_titleBa);
        titleBar.setTitle("问题反馈", 0);
        titleBar.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });


        edit = (EditText) findViewById(R.id.feedback_edit);
        gv = (GridView) findViewById(R.id.feedback_gv);

        bt_release = (Button) findViewById(R.id.feedback_bt_release);
        bt_release.setOnClickListener(this);

        feedback_phone_ln = (LinearLayout) findViewById(R.id.feedback_phone_ln);
        feedback_phone = (EditText) findViewById(R.id.feedback_phone);

        choose_rl = (RelativeLayout) findViewById(R.id.feedback_choose_rl);
        choose_rl.setOnClickListener(this);

        initData();
    }

    private void initData(){
        adapter = new FeedbakAdapter(this);
        gv.setAdapter(adapter);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(FeedbackDetailActivity.this, FastChoosePhotoActivity.class);
                intent.putParcelableArrayListExtra("choose_image", medias);
                intent.putExtra(BaseConfig.MAX, 4);//最多四张图片
                startActivityForResult(intent, 0);
            }
        });

        if (UCommonUtil.getUtil().isLogin()){
            phoneString = SPUtils.getPreferences(this).getUserName();
            if (!TextUtils.isEmpty(phoneString)){
                feedback_phone.setText(phoneString);
            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.feedback_bt_release:
                //发布
                editContent = edit.getText().toString();
                phoneString = feedback_phone.getText().toString();

                if (TextUtils.isEmpty(editContent) && medias.size() <1){
                    UCommonUtil.getUtil().showToast(this, "请描述问题出现的场景");
                    return;
                }
                if (TextUtils.isEmpty(phoneString) ){
                    UCommonUtil.getUtil().showToast(this, "请填写联系方式");
                    return;
                }

                LoadingUtils.getUtils().loading(this);
                if (imageList != null && imageList.size() >0){
                    ImageManagerUtils.getUtils().compressAndPost(this, OSSManager.OSS_CITY, imageList, 300, false,new ImageManagerUtils.ImageCompressListener() {
                        @Override
                        public void onResult(int stutas, String cover, String result) {
                            if (stutas !=0){
                                if (stutas ==-1){
                                    //压缩失败 可以直接上传原图
                                }
                                LoadingUtils.getUtils().hide();
                                UCommonUtil.getUtil().showToast(FeedbackDetailActivity.this, "上传失败, 请重试");
                                return;
                            }
                            //压缩上传oss成功 将信息上传到自己服务器
                            postToServer(result);
                        }
                    });
                }else {
                    postToServer("");
                }

                break;

            case R.id.feedback_choose_rl:
                //选择图片
                chooseImage();
                break;
        }
    }

    /**
     * 将反馈信息提交到服务器
     * */
    private void postToServer(String images){
//        if (UChengApplication.userRole == BaseConfig.UNI_ROLE){
//            //Uni提交反馈
//            HttpUniManager.getManager().postFeedback(this, pubTitle + "   "+editContent, images);
//        }else {
            MapRequest map = new MapRequest();
            map.put(BaseConfig.APP_VERSION, UCommonUtil.getUtil().getVersionName(this));
            map.put(BaseConfig.CONTACT, phoneString);
            map.put(BaseConfig.ADVICE_TYPE, pubTitle);
            map.put(BaseConfig.DESCRIPTION, "手机品牌="+ Build.BRAND+"=手机型号="+Build.MODEL+":  "+editContent);
            if (!TextUtils.isEmpty(images)){
                map.put(BaseConfig.IMSGES, images);
            }
            map.put(BaseConfig.OPERATING_SYSTEM, "android");
            if (UCommonUtil.getUtil().getId() >0){
                map.put(BaseConfig.UID, UCommonUtil.getUtil().getId());
            }

            HttpManager.newInstance(this).query(UCityConfig.Feedback.method, UCityConfig.Feedback.URL, map, new HttpCallBack() {
                @Override
                public void onError(int status, String msg) {
                    LoadingUtils.getUtils().hide();
                    Log.d("jjf", "stutas="+status+"=msg="+msg);
                    UCommonUtil.getUtil().showToast(FeedbackDetailActivity.this, "提交失败");
                }

                @Override
                public void onResp(int status, String msg, String data) {
                    LoadingUtils.getUtils().hide();
                    Log.d("jjf", "stutas="+status+"=msg="+msg);
                    if (status != 0){
                        UCommonUtil.getUtil().showToast(FeedbackDetailActivity.this, msg);
                        return;
                    }
                    UCommonUtil.getUtil().showToast(FeedbackDetailActivity.this, "提交成功, 谢谢你的反馈");
                    FeedbackDetailActivity.this.finish();

                }
            });
//        }


    }



    /**
     * 选择图片
     * */
    private void chooseImage(){
        UCommonUtil.getUtil().openGalleryMultiple(this, 4,new RxBusResultSubscriber<ImageMultipleResultEvent>() {
            @Override
            public void onEvent(ImageMultipleResultEvent event)  {
                //选择图片点击确定完成时的操作
                int num = 0;
                if (event.getResult() != null){
                    num = event.getResult().size();
                    medias.clear();
                    medias.addAll(event.getResult());

                    if (num > 0){
                        Intent intent = new Intent(FeedbackDetailActivity.this, FastChoosePhotoActivity.class);
                        intent.putParcelableArrayListExtra("choose_image", medias);
                        intent.putExtra(BaseConfig.MAX, 4);//最多四张图片
                        startActivityForResult(intent, 0);
                    }
                }
            }
        },null, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxGalleryListener.getInstance().setMultiImageCheckedListener(null);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private AlertDialog dialog;
    private void back(){
        if (!TextUtils.isEmpty(edit.getText().toString()) || medias.size() >0){
            dialog = DialogUtils.getUtils().showDialogSingle(this, "确定取消反馈?", "确定", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DialogUtils.getUtils().cancel();
                    FeedbackDetailActivity.this.finish();
                }
            });
        }else {
            FeedbackDetailActivity.this.finish();
        }
    }

    //得到本地返回的图片地址集合 提交到oss
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imageList = new ArrayList<>();
        imageList.clear();
        if (requestCode == 0 && resultCode == 1){
            medias = data.getParcelableArrayListExtra("choose_image");
            if (medias != null && medias.size()>0){
                for (MediaBean bean : medias){
                    if (!TextUtils.isEmpty(bean.getThumbnailBigPath())){
                        imageList.add(bean.getThumbnailBigPath());
                        Log.d("jjj", "图片大小="+bean.getThumbnailBigPath());
                    }else {
                        imageList.add(bean.getOriginalPath());
                    }
                }

                choose_rl.setVisibility(View.GONE);
                gv.setVisibility(View.VISIBLE);

                adapter.setData(imageList);

            }else {
                choose_rl.setVisibility(View.VISIBLE);
                gv.setVisibility(View.GONE);

            }
        }
    }
}
